package com.example.lin.day10_17_bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;

public class MainServerActivity extends AppCompatActivity {

    private static final String TAG = MainServerActivity.class.getSimpleName();
    //蓝牙适配器
    private BluetoothAdapter defaultAdapter;
    private View ll_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ll_back = findViewById(R.id.ll_back);
        //获取蓝牙适配器
        defaultAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    public void openBluetooth(View view) {
        if (defaultAdapter != null) {
            Toast.makeText(this, "手机支持蓝牙", Toast.LENGTH_SHORT).show();
            //判断蓝牙是否打开
//            if (!defaultAdapter.isEnabled()) {
//                //请求打开蓝牙
//                startActivity(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));
//            }
            //判断蓝牙是否打开
            if (!defaultAdapter.isEnabled()) {
                //强制打开蓝牙,在高版本(6.0以上) 还是会弹出提示框请求用户同意
                defaultAdapter.enable();
            }


        } else {
            Toast.makeText(this, "手机不支持蓝牙", Toast.LENGTH_SHORT).show();
        }
    }

    public void discoverableBluetooth(View view) {
        //判断蓝牙是否打开
        if (defaultAdapter.isEnabled()) {
            //请求蓝牙可以被发现(7.0之后,打开蓝牙默认可被发现)
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            //配置蓝牙可被发现的时长(/s)
            intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 180);
            startActivity(intent);
            //监听等待客户端的连接
            listenerClientConnection();
        }
    }

    private Handler h = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            int color = msg.what;
            ll_back.setBackgroundColor(color);
            return false;
        }
    });

    private BluetoothSocket lastAccept;

    /**
     * 监听等待客户端的连接
     */
    private void listenerClientConnection() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                if (defaultAdapter != null) {
                    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
                    //服务端Socket
                    BluetoothServerSocket serverSocket = null;
                    try {
                        serverSocket = defaultAdapter.listenUsingRfcommWithServiceRecord("server", uuid);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    while (serverSocket != null) {
                        try {
                            Log.d(TAG, "run: 等待客户端连接中.....");
                            //客户端的 Socket 对接对象
                            BluetoothSocket accept = serverSocket.accept();//阻塞等待客户端连接
                            if (lastAccept != null) {
                                continue;
                            }
                            lastAccept = accept;
                            Log.d(TAG, "run: 与客户端连接成功.....");
                            //与客户端建立 IO流. 输入流
//                        BufferedReader br = new BufferedReader(new InputStreamReader(accept.getInputStream(), "UTF-8"));
                            InputStream is = accept.getInputStream();
                            DataInputStream dataInputStream = new DataInputStream(is);
                            while (true) {
                                Log.d(TAG, "run: 等待客户端发送数据...");
                                int read = dataInputStream.readInt();
                                if (read == -1) {
                                    break;
                                }
                                Log.i(TAG, "run: 接收到客户端发送过来的数据..." + read);
                                //得到的每一行字符串都是客户端发送过来的颜色值  int值
                                h.sendEmptyMessage(read);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            lastAccept = null;
                        }
                    }

                }
            }
        }).start();


    }

}
